package com.lidastudio.dbdatamock.shell;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.concurrent.CyclicBarrier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import com.lidastudio.dbdatamock.dto.DatabaseInfo;
import com.lidastudio.dbdatamock.service.IDatabaseService;
import com.lidastudio.dbdatamock.thread.MockThread;
import com.lidastudio.dbdatamock.util.DatabaseUtil;
import com.zaxxer.hikari.HikariDataSource;

@ShellComponent
public class MainShell {
	@Autowired
	private IDatabaseService databaseService;
	
	@ShellMethod("随机生成数据库表数据")
	public String mock(
			@ShellOption( help="Database Host" , defaultValue = "localhost")String dbHost,
			@ShellOption( help="Database Port" , defaultValue = "3306")Integer dbPort,
			@ShellOption( help="Database Account" , defaultValue = "root")String dbUsername,
			@ShellOption( help="Database Password" , defaultValue = "root")String dbPassword,
			@ShellOption( help="Database Name" )String databaseName,
			@ShellOption( help="Table Name" )String tableName,
			@ShellOption( help="Count of Mock Data" )Long mockCount,
			@ShellOption( help="Batch Insert Size", defaultValue="300" )Integer batchSize,
			@ShellOption( help="Thread Count", defaultValue="8" )Integer threadCount
			
	) throws Exception {
		long startTime = System.currentTimeMillis();
		DatabaseInfo databaseInfo = new DatabaseInfo(dbHost,dbPort, dbUsername, dbPassword);
		HikariDataSource ds = DatabaseUtil.getDataSource(databaseInfo.getHost(), databaseInfo.getPort(), databaseName, databaseInfo.getUsername(), databaseInfo.getPassword());
		
		CyclicBarrier cb = new CyclicBarrier(threadCount,new Runnable() {

			@Override
			public void run() {
				long endTime = System.currentTimeMillis();
				System.out.println((endTime-startTime) + " mill sec.");
				if( ds != null ) {
					ds.close();
				}				
			}
			
		});
		for(int i = 0 ; i < threadCount; i++ ) {
			new MockThread(
					databaseService,
					ds, 
					databaseName, 
					tableName,
					mockCount,
					batchSize,
					cb).start();
		}
		
		return "Success";
	}

}
